package com.carltechnology.mahjonggamecaculation.presenter.impl;

import android.content.Intent;
import android.support.design.widget.Snackbar;
import android.view.View;

import com.carltechnology.mahjonggamecaculation.base.MyAbstractSubscriber;
import com.carltechnology.mahjonggamecaculation.mode.IGameRuntimeData;
import com.carltechnology.mahjonggamecaculation.mode.impl.GameRuntimeDataMode;
import com.carltechnology.mahjonggamecaculation.presenter.IMahjongPerGameInputPresenter;
import com.carltechnology.mahjonggamecaculation.utils.Utils;
import com.carltechnology.mahjonggamecaculation.views.IMahjongGamePerInputView;
import com.carltechnology.mahjonggamecaculation.views.impl.MahjongGamePerInputActivity;
import com.carltechnology.mahjonggamecaculation.views.impl.MahjongRunningGameActivity;

import java.util.Arrays;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by WZTCM on 2016/6/30.
 */
public class MahjongPerGameInputPresenter implements IMahjongPerGameInputPresenter {
    private static final String TAG = MahjongPerGameInputPresenter.class.getSimpleName();
    private IMahjongGamePerInputView mView;
    // runtimeData的注入id
    private int id;
    // 注入的位置号
    private int pos;
    private MyPerGameSubs mySubs;
    private static MahjongPerGameInputPresenter instance ;
    private MahjongPerGameInputPresenter() {
        mySubs = new MyPerGameSubs();
        getPerDetectObservable().subscribe(mySubs);
    }
    private void injectData(IMahjongGamePerInputView mView,int id,int pos){
        this.mView = mView;
        this.id = id;
        this.pos = pos ;
    }
    @Override
    public int getPerUnit() {
        return 0;
    }

    @Override
    public void examineAndStoreMahjongGameInfo() {
        String [] contents = mView.getContents();
        mySubs.listSubs.onNext(Arrays.asList(contents));

    }

    @Override
    public void doDestroy() {
        mySubs.onCompleted();
        mySubs = null;
        instance = null;
    }

    private Observable<IGameRuntimeData> getPerDetectObservable(){
        return Observable.create(new Observable.OnSubscribe<List<String>>() {
            @Override
            public void call(Subscriber<? super List<String>> subscriber) {
                mySubs.listSubs = subscriber;
            }
        })
                .onBackpressureBuffer(Utils.CONSTANT.ONBACKBUFFER_SMALL_SIZE.getConstant())
                .subscribeOn(Schedulers.computation())
                .observeOn(Schedulers.computation())
                // filter the empty msg
                .filter(new Func1<List<String>, Boolean>() {
                    @Override
                    public Boolean call(List<String> list) {
                        if (list.size()!=5){
                            return false;
                        }
                        for (int i=0;i<5;i++){
                            if (Utils.getInstance().stringIsEmpty(list.get(i))){
                                mView.getHandler().post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Snackbar.make(mView.getContainer(),
                                                MahjongGamePerInputActivity.PERGAME_MSG.PRICE_NOTHING.toString(),
                                                Snackbar.LENGTH_SHORT)
                                                .setAction("Undo", new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {

                                                    }
                                                })
                                                .show();
                                    }
                                });
                                return false;
                            }
                        }
                        return true;
                    }
                })
                .map(new Func1<List<String>, IGameRuntimeData>() {
                    @Override
                    public IGameRuntimeData call(List<String> list) {
                        int []prices = new int [4];
                        int cost;
                        for (int i=0;i<4;i++){
                            prices[i] = Integer.parseInt(list.get(i));
                        }
                        cost = Integer.parseInt(list.get(4));


                        return GameRuntimeDataMode._of(id,prices,cost);
                    }
                })
                .filter(new Func1<IGameRuntimeData, Boolean>() {
                    @Override
                    public Boolean call(IGameRuntimeData data) {
                        int [] prices = data.getGameCount();
                        int cost = data.getCost();
                        if (cost<0){
                           // myView.sendMsgToFragment(MahjongPerGameInputFragment.PERGAME_MSG.COST_NOTHING);
                            mView.getHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Snackbar.make(mView.getContainer(),
                                            MahjongGamePerInputActivity.PERGAME_MSG.COST_NOTHING.toString(),
                                            Snackbar.LENGTH_SHORT)
                                            .setAction("Undo", new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {

                                                }
                                            })
                                            .show();
                                }
                            });
                            return false;
                        }
                        /**
                         * 计算平衡因子
                         */
                        int balance = 0;
                        for (int i=0;i<prices.length;i++){
                            balance += prices[i];
                        }
                        balance += cost;
                        //myView.sendBalanceFactorToFragment(balance);
                        final int res = balance;
                        mView.getHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                mView.getBalanceView().setText(String.valueOf(res));
                            }
                        });
                        /**
                         * 平衡因子不为0，则表示其无效
                         */
                        if (balance!=0){
                            //myView.sendMsgToFragment(MahjongPerGameInputFragment.PERGAME_MSG.BALANCE_UNRIHGT);
                            mView.getHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Snackbar.make(mView.getContainer(),
                                            MahjongGamePerInputActivity.PERGAME_MSG.BALANCE_UNRIHGT.toString(),
                                            Snackbar.LENGTH_SHORT)
                                            .setAction("Undo", new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {

                                                }
                                            })
                                            .show();
                                }
                            });
                            return false;
                        }
                        return true;
                    }
                }).observeOn(AndroidSchedulers.mainThread());
    }

    private class MyPerGameSubs extends MyAbstractSubscriber<IGameRuntimeData>{
        Subscriber<? super List<String>> listSubs;

        @Override
        public void onCompleted() {
            super.onCompleted();
        }

        @Override
        public void onNext(IGameRuntimeData iGameRuntimeData) {
            Intent intent = new Intent();
            int res = MahjongRunningGameActivity.INTENT_CODE.REQUEST_RUNNING_CODE.getResult();
            intent.putExtra(MahjongRunningGameActivity.PARCEL_NAME,iGameRuntimeData);
            if (pos!=-1){
                res = MahjongRunningGameActivity.INTENT_CODE.REQUEST_MODIFY_CODE.getResult();
                intent.putExtra(MahjongRunningGameActivity.POS_NAME,pos);
            }
            mView.getActivity()
                    .setResult(res,
                            intent);
            mView.getActivity().finish();
            clear();

        }
    }

    public static IMahjongPerGameInputPresenter getInstance(IMahjongGamePerInputView view,int id,int pos){
        if (instance == null){
            instance = new MahjongPerGameInputPresenter();
        }
        instance.injectData(view, id,pos);
        return instance;
    }
    private void clear(){
        mView = null;
        id = -1;
        pos=-1;
    }
}
